<?php
$dbh = new PDO('mysql:host=localhost;dbname=newsletter_development' ,
                'root' , '' );
// Check if the email format is valid
function emailValid($email) {
    $pattern = '/^[a-z0-9_.-]+@[a-z0-9-]+\.[a-z.]+$/i' ;
    return preg_match($pattern, $email);
}
// Check if a user is already subscribed
function subscriberExists($dbh, $email) {
    $sql = "SELECT COUNT(*) AS cnt FROM subscribers
             WHERE email=".$dbh->quote($email);
    $row = $dbh->query($sql)->fetch();
    return !empty($row['cnt' ]);
}
// Insert a new subscriber into the list
function insertSubscriber($dbh, $email) {
    $sql = "INSERT INTO subscribers (email)
            VALUES (".$dbh->quote($email).")";
    return $dbh->exec($sql);
}

// Get list of subscribers
function getSubscribers($dbh) {
    $sql = "SELECT email FROM subscribers";
    $subs = $dbh->query($sql)->fetchAll();
    //echo "hello from getSubscribers";
    //print_r($subs);
    return $subs;
}

$subscribers = getSubscribers($dbh);
$error = '' ;
$success = '' ;
$email = isset($_POST['email' ]) ? $_POST['email' ] : '' ;
if ($_SERVER['REQUEST_METHOD' ] == 'POST' ) {
    if (!emailValid($email)) {
        $error = "Email is an invalid format. Please try again.";
    } elseif (subscriberExists($dbh, $email)) {
        $error = "Email already exists on our list.";
    } elseif (insertSubscriber($dbh, $email)) {
        $success = "Thank you, You have been subscribed.";
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head><title>Subscribe to our Mailing List</title></head>
  <body>
    <h2>Current Subscribers</h2>
    <div>
        <?php 
            //print_r($subscribers);
            //echo '<br />';
            foreach($subscribers as $email) {
                echo htmlentities($email['email'], ENT_QUOTES); 
                echo '<br />';
            }
        ?>
    </div>
    <hr>

    <h2>Subscribe to our Mailing List</h2>
    <div style="color: red">
       <?php echo htmlentities($error, ENT_QUOTES) ?>
    </div>
    <div style="color: green">
       <?php echo htmlentities($success, ENT_QUOTES) ?>
    </div>

    <form method="post" action="/newsletter.php">
      <input type="text" name="email" size="25" />
      <input type="submit" />
    </form>
  </body>
</html>


